<template>
  <div class="ccui-home-index">
    <div class="ccui-app-container">
      <!-- 高级搜索 -->
      <div class="ccui-advanced-search-wrapper ccui-clearfix">
        <el-search
          ref="search"
          :formProp="formData"
          @search="searchItem"
          @change="change"
          :isShowSearch="true"
          :selectClear="true"
          class="ccui-highsearch no-print"
        >
          <div class="ccui-tab-wrapper">
            <el-button
              type="table-top-active"
              size="mini"
              @click="tabChange(1)"
            >
              全部({{ totalNum }})
            </el-button>
            <el-button type="table-top" size="mini" @click="tabChange(0)">
              待提交
            </el-button>
            <el-button type="table-top" size="mini" @click="tabChange(2)">
              审批中
            </el-button>
            <el-button type="table-top" size="mini" @click="tabChange(3)">
              审批退回
            </el-button>
          </div>
          <div class="ccui-extend-btn">
            <el-button
              type="primary"
              ref="pcconclease-new-item"
              @click="handleGoNew"
              icon="icon-ccui-add-sup"
              >新增
            </el-button>
          </div>
          <template slot="search">
            <el-input
              v-model="formData.invoiceName"
              clearable
              searchLabel="发票单名称"
              placeholder="请输入发票单名称模糊查询"
            ></el-input>
            <el-input
              v-model="formData.invoiceCode"
              clearable
              searchLabel="发票单编号"
              placeholder="请输入发票单编号模糊查询"
            ></el-input>
            <el-input
              v-model="formData.settlementName"
              clearable
              searchLabel="结算单名称"
              placeholder="请输入结算单名称模糊查询"
            ></el-input>
            <el-input
              v-model="formData.settlementCode"
              clearable
              searchLabel="结算单编号"
              placeholder="请输入结算单编号模糊查询"
            ></el-input>
            <el-input
              v-model="formData.partyBName"
              clearable
              searchLabel="供应商"
              placeholder="请输入供应商模糊查询"
            ></el-input>

            <el-input
              v-model="formData.reportInOrgName"
              clearable
              searchLabel="填报单位"
              placeholder="请输入填报单位模糊查询"
            ></el-input>

            <el-select
              v-model="formData.enterStatus"
              placeholder="请选择状态查询"
              searchLabel="状态"
            >
              <el-option
                v-for="(item, status) in smpScStatusTypeName"
                :key="status + '1'"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </template>
          <el-input
            v-model="formData.invoiceName"
            clearable
            searchLabel="发票单名称"
            placeholder="请输入发票单名称模糊查询"
            slot="searchItem2"
          />
          <el-input
            v-model="formData.invoiceCode"
            clearable
            searchLabel="发票单编号"
            placeholder="请输入发票单编号模糊查询"
            slot="searchItem1"
          />
          <el-input
            v-model="formData.settlementName"
            clearable
            searchLabel="结算单名称"
            placeholder="请输入结算单名称模糊查询"
            slot="searchItem10"
          ></el-input>
          <el-input
            v-model="formData.settlementCode"
            clearable
            searchLabel="结算单编号"
            placeholder="请输入结算单编号模糊查询"
            slot="searchItem11"
          ></el-input>
          <el-input
            v-model="formData.partyBName"
            clearable
            searchLabel="供应商"
            placeholder="请输入供应商模糊查询"
            slot="searchItem3"
          />

          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
            slot="searchItem4"
          />

          <el-select
            v-model="formData.enterStatus"
            placeholder="请选择状态查询"
            searchLabel="状态"
            slot="searchItem5"
          >
            <el-option
              v-for="(item, ind) in smpScStatusTypeName"
              :key="ind + '2'"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-search>
      </div>
      <div class="ccui-multifunctional-table-wrapper">
        <el-table
          ref="multipleTable"
          :data="tableData"
          :fit="true"
          border
          class="ccui-multifunctional-table"
          :cell-style="cellStyle"
          @cell-click="cellClick"
          @selection-change="handleSelectionChange"
          @header-dragend="setTableTitleWidth"
          max-height="20000"
        >
          <template v-for="(table, index) in tableTheadOptions">
            <el-table-column
              v-if="table.checked"
              :fixed="table.fixed"
              :key="index"
              :type="table.type"
              :label="table.label"
              :min-width="table.width"
              :prop="table.prop"
              :align="table.align || 'left'"
              :formatter="formatterList[table.formatterName]"
              :header-align="table.headerAlign || 'left'"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </template>

          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleGoEdit(scope.row)"
                v-if="
                  scope.row.enterStatus == '待提交' ||
                    scope.row.enterStatus == '审批退回' ||
                    scope.row.enterStatus == '已撤回'
                "
                >编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-if="
                  scope.row.enterStatus == '待提交' ||
                    scope.row.enterStatus == '已撤回'
                "
                >删除
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleReturn(scope.row)"
                v-if="scope.row.enterStatus == '审批中'"
                >撤回
              </el-button>
            </template>
            <!-- <template v-slot:header>
              <div
                class="
                                    ccui-multifunctional-table-wrapper-operation
                                "
              >
                <span>操作</span>
                <el-popover
                  placement="right"
                  popper-class="ccui-multifunctional-table-wrapper_setting__popover"
                  trigger="click"
                >
                  <el-checkbox
                    v-for="(e, i) in fixedTableThead"
                    :key="i"
                    :checked="e.checked"
                    disabled
                    class="ccui-popover-disabled"
                    >{{ e.label }}
                  </el-checkbox>
                  <el-button
                    size="mini"
                    type="primary-font-mini"
                    class="
                                            ccui-multifunctional-table-wrapper_setting__reset
                                        "
                    @click="resetTableColumn"
                    >重置</el-button
                  >
                  <div class="ccui-popover-line"></div>
                  <draggable
                    :list="unfixedTableThead"
                    class="ccui-draggable"
                    @change="handleTableChange"
                  >
                    <el-checkbox-group
                      v-for="(item, index) in unfixedTableThead"
                      v-model="item.checked"
                      :key="index"
                    >
                      <el-checkbox
                        :label="item"
                        :checked="item.checked"
                        :width="item.width"
                        :title="item.label"
                        @change="handleUpdate(item, index)"
                        >{{ item.label }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </draggable>
                  <i
                    class="
                                            el-icon-s-tools
                                            ccui-multifunctional-table-wrapper_setting__icon
                                        "
                    slot="reference"
                  ></i>
                </el-popover>
              </div>
            </template> -->
          </el-table-column>
        </el-table>

        <div class="ccui-table-footer" v-show="isShowPagination">
          <div id="ccui-paging">
            <el-pagination
              :total="totalNum"
              :page-size="pageSizeCode"
              :current-page="pageNoCode"
              :page-sizes="[10, 20, 50, 100, 200, 500]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              popper-class="ccui-paging-page-size-popper"
              @prev-click="handlePrev"
              @next-click="handleNext"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-button
              class="ccui-pagination-btn"
              size="mini"
              type="default"
              @click="handleSizeChange('none')"
              >确定</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { formatNumber } from "../../../../basa/utils";
// import draggable from "vuedraggable";
// import { setSessionItem, getSessionItem } from "@/basa/utils";
import { getInvoiceStoreList, removeInvoceBasic, revokeInvoice } from "../api";
export default {
  name: "list_toSubmit",
  components: {
    // draggable
  },
  created() {
    this.init();
  },
  data() {
    return {
      isShowPagination: true,
      pageSizeCode: 1,
      pageNoCode: 1,
      pagesize: 10,
      formhSearchData: {},
      localSearchData: "",
      formData: {
        invoiceCode: "",
        invoiceName: "",
        partyBName: "",
        reportInOrgName: "",
        settlementCode: "",
        settlementName: "",
        enterStatus: ""
      },
      smpScStatusTypeName: {
        2: "待提交", //编辑中
        3: "审批中", // 审批中
        4: "已撤回", // 已撤回
        5: "审批通过", // 审批通过
        6: "审批退回", // 审批退回
        // 7: "审批不通过", // 审批不通过
        // 21: "冲销中", // 冲销中
        22: "已冲销" // 已冲销
      },
      // table相关
      // Todo 表格数据 start
      tableData: [{}],
      tableThead: [],
      tableName: this.tableList.invoiceEntering,
      // 锁定表格
      fixedTableThead: [
        {
          label: "序号",
          width: 39,
          checked: true,
          fixed: "left",
          type: "index"
        },
        {
          label: "发票单编号",
          prop: "invoiceCode",
          width: "150",
          fixed: "left",
          checked: true
        }
      ],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "发票单名称",
          prop: "invoiceName",
          width: "300",
          checked: true
        },
        {
          label: "供应商",
          prop: "partyBName",
          width: "200",
          checked: true
        },
        // {
        //   label: "合同签订单位",
        //   prop: "contractSignDeptName",
        //   width: "200",
        //   checked: true
        // },
        {
          label: "结算单编号",
          prop: "settlementCode",
          width: "150",
          checked: true
        },
        {
          label: "结算单名称",
          prop: "settlementName",
          width: "300",
          checked: true
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200",
          checked: true
        },
        {
          label: "发票金额(含税)",
          prop: "currentInvoiceAmount",
          width: "140",
          checked: true,
          align: "right"
        },
        {
          label: "编制人",
          prop: "compileUser",
          width: "60",
          checked: true
        },
        {
          label: "编制日期",
          prop: "compileDate",
          width: "100",
          checked: true,
          formatterName: "compileDate"
        },
        {
          label: "不含税金额",
          prop: "amountExcludeTax",
          width: "130",
          checked: true,
          align: "right"
        },
        {
          label: "税额",
          prop: "tax",
          width: "130",
          checked: true,
          align: "right"
        },
        {
          label: "币种",
          prop: "currency",
          width: "130",
          checked: true
        },
        {
          label: "状态",
          prop: "enterStatus",
          width: "70",
          checked: true,
          formatterName: "enterStatus"
        }
      ],
      // 动态表格
      tableTheadOptions: [],
      formatterList: {
        compileDate(row) {
          if (row.compileDate) {
            let newCompileDate = row.compileDate.substring(0, 10);
            return newCompileDate;
          }
        }
      },
      totalNum: 0,
      isFocus: "2",
      contractState: "2"
    };
  },
  activated() {
    (this.formData = {
      invoiceCode: "",
      invoiceName: "",
      partyBName: "",
      reportInOrgName: "",
      settlementCode: "",
      settlementName: "",
      enterStatus: ""
    }),
      (this.formhSearchData = {});
    this.getInvoiceList();
    this.$refs.search.resetForm();
    this.pageNoCode = 1;
  },
  methods: {
    getInvoiceList(reqObj) {
      let ienterStatus = "";
      if (this.formData.enterStatus == "待提交") {
        ienterStatus = "2";
      } else if (this.formData.enterStatus == "已撤回") {
        ienterStatus = "4";
      } else if (this.formData.enterStatus == "审批通过") {
        ienterStatus = "5";
      } else if (this.formData.enterStatus == "审批退回") {
        ienterStatus = "6";
      } else if (this.formData.enterStatus == "已冲销") {
        ienterStatus = "22";
      } else if (this.formData.enterStatus == "审批中") {
        ienterStatus = "3";
      }
      // var obj = this.formData;
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.enterStatus = ienterStatus;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pagesize;
      // console.log("obj",obj);
      getInvoiceStoreList({
        ...obj
        //   enterStatus: "6",
        // pageNo: this.pageNoCode,
        // pageSize: this.pagesize
      }).then(res => {
        this.tableData = res.data.data.rows;
        this.tableData.forEach(item => {
          item.enterStatus = this.smpScStatusTypeName[item.enterStatus];
          item.tax = Number(item.tax).toFixed(2);
          item.currentInvoiceAmount = Number(item.currentInvoiceAmount).toFixed(
            2
          );
          item.amountExcludeTax = Number(item.amountExcludeTax).toFixed(2);
        });

        this.totalNum = res.data.data.recordsTotal;
      });
    },
    // 获取默认分页
    // getLocalPageSize() {
    //   return getSessionItem("pageSize", this.tableList.invoicereversal) || 10;
    // },

    handleSizeChange(val) {
      this.pagesize = val;
      // this.searchItem(this.formhSearchData);
      this.getInvoiceList(this.formhSearchData);
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.pageNoCode = val;
      // console.log("this.pageNoCode",this.pageNoCode);
      // this.searchItem(this.formhSearchData);
      this.getInvoiceList(this.formhSearchData);

      // console.log(`当前页: ${val}`);
    },
    internalCurrentPage(val) {
      val = 10;
      // console.log(`当前22页: ${val}`);
    },
    handlePrev() {},
    handleNext() {},
    handleGoPage() {},

    init() {
      this.setTableWidth();
      this.renderTable();
    },
    // 跳转编辑页
    handleGoEdit(r) {
      this.$router.push({
        path: "/invoice/Entering/invoiceEdit/" + r.id,
        query: {
          enterStatus: r.enterStatus,
          invoiceName: r.invoiceName
        }
      });
    },
    handleDelete(row) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      }).then(() => {
        removeInvoceBasic({ ids: [row.id] }).then(res => {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true
          });
          this.getInvoiceList();
        });
      });
    },
    // 跳转新增页
    handleGoNew() {
      this.$router.push({
        path: "/invoice/Entering/invoiceAdd",
        query: {
          enterStatus: ""
        }
      });
    },
    searchItem(reqObj) {
      // let ienterStatus = "";
      // if (this.formData.enterStatus == "待提交") {
      //   ienterStatus = "2";
      // } else if (this.formData.enterStatus == "已撤回") {
      //   ienterStatus = "4";
      // } else if (this.formData.enterStatus == "审批通过") {
      //   ienterStatus = "5";
      // } else if (this.formData.enterStatus == "审批退回") {
      //   ienterStatus = "6";
      // } else if (this.formData.enterStatus == "已冲销") {
      //   ienterStatus = "22";
      // } else if (this.formData.enterStatus == "审批中") {
      //   ienterStatus = "3";
      // };

      this.pageNoCode = 1;
      this.formhSearchData = reqObj;
      // console.log("this.formhSearchData ",this.formhSearchData );
      // this.localSearchData = JSON.parse(JSON.stringify(reqObj));
      // setSessionItem("pageNo", this.tableName, {
      //   pageNo: this.pageNoCode,
      //   searchForm: this.localSearchData
      // });

      // let obj = {};
      // obj = typeof reqObj == "object" ? reqObj : obj;
      // obj.enterStatus = ienterStatus;
      // obj.pageNo = this.pageNoCode;
      // obj.pageSize = this.pagesize;
      // // console.log("obj",obj);
      // getInvoiceStoreList({
      //   ...obj,
      //   // enterStatus: ienterStatus,
      //   // pageNo:  this.pageNoCode,
      //   // pageSize: this.pagesize
      // }).then(res => {
      //   this.tableData = res.data.data.rows;
      //   this.tableData.forEach(
      //     item =>
      //       (item.enterStatus = this.smpScStatusTypeName[item.enterStatus])
      //   );
      //   this.totalNum = res.data.data.recordsTotal;
      // });
      this.getInvoiceList(reqObj);
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    resetTableColumn() {
      localStorage.removeItem(this.tableName);
      this.reload();
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.unfixedTableThead.concat(
        this.fixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, width, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          this.unfixedTableThead = localTableData.filter(item => {
            return !this.fixedTableThead.find(
              cItem => item.prop === cItem.prop
            );
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 表格弹框拖拽触发
    handleTableChange(val) {
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 是否显示对应列
    handleUpdate(item, index) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (i === index) {
          this.unfixedTableThead.checked = !this.unfixedTableThead.checked;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    setTableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
    },
    handleSelectionChange(data) {
      this.selectData = data;
    },
    // 撤回
    handleReturn(row) {
      this.$confirm("您确定要撤回吗？", "撤回确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      }).then(() => {
        revokeInvoice({ id: row.id }).then(res => {
          if (res.data.code == "0") {
            this.getInvoiceList();
          }
        });
      });
    },
    tabChange(index) {
      switch (index) {
        case 1:
          this.$router.push("/invoice/Entering/list-all");
          break;
        case 0:
          this.$router.push("/invoice/Entering/toSubmit");
          break;
        case 2:
          this.$router.push("/invoice/Entering/list-pendding");
          break;
        case 3:
          this.$router.push("/invoice/Entering/list-return");
          break;
      }
    },
    cellClick(row, column) {
      if (column.label === "发票单编号") {
        console.log("点击的行信息", row);
        let newEnterStatus;
        if (row.enterStatus === "已冲销") {
          newEnterStatus = "22";
        } else if (row.enterStatus === "审批通过") {
          newEnterStatus = "5";
        } else {
          newEnterStatus = row.enterStatus;
        }
        this.$router.push({
          path: "/invoice/Entering/list-check",
          query: {
            myId: row.id,
            enterApproveStatus: newEnterStatus,
            invoiceName: row.invoiceName
          }
        });
      }
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (["invoiceCode"].includes(column.property)) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    }
  }
};
</script>

<style scoped></style>
